# coding = 'utf-8'

import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QGridLayout, QLineEdit

from PyQt5.QtCore import Qt


class Example(QWidget):
    # 存储以前的数据，用来判断是否存在=，存在则重新输入数字进行计算
    store_char = ""

    def __init__(self):
        super().__init__()
        self.Init_UI()

    def Init_UI(self):
        grid = QGridLayout()
        self.setLayout(grid)

        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle("计算器")

        # 创建显示区域
        self.display = QLineEdit()

        self.display.setAlignment(Qt.AlignmentFlag.AlignRight)  # 设置QLineEdit 中字符串对齐方式
        # self.display.setStyleSheet("")
       
        self.display.setFixedHeight(80)   # 设置display文本框高度
        grid.addWidget(self.display, 0, 0, 1, 4)
        grid.setSpacing(10)
        # 按钮文本及其位置
        names = [
            "Cls",
            "Del",
            "",
            "Close",
            "7",
            "8",
            "9",
            "/",
            "4",
            "5",
            "6",
            "*",
            "1",
            "2",
            "3",
            "-",
            "0",
            ".",
            "=",
            "+",
        ]

        positions = [(i, j) for i in range(4, 9) for j in range(0, 4)]
        for position, name in zip(positions, names):
            if name == "":
                continue
            button = QPushButton(name)
            grid.addWidget(button, *position)
            button.clicked.connect(self.Cli)

        self.show()

    def Cli(self):
        sender = self.sender().text()
        old_str = self.display.text()
        self.store_char += old_str + sender
        print(self.store_char)

        if sender == "=":
            num = eval(self.display.text())
            self.store_char + str(num)
            self.display.setText(str(num))
        elif sender == "Cls":
            self.display.clear()
            self.store_char = ""
            self.display.setText("0")

        elif sender == "Del":

            strLen = len(old_str)
            if strLen > 1:
                new_str = old_str[0 : strLen - 1]
                self.display.setText(new_str)
            else:
                self.display.setText("0")

        else:
            if "=" in self.store_char:
                self.store_char = ""
                self.display.setText(sender)

            else:
                if old_str != "0":

                    self.display.setText(old_str + sender)
                else:
                    self.display.setText(sender)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = Example()
    app.exit(app.exec_())
